<template>
    <lay-card width="1200" style="height: 800px">
      <lay-row space="20">
        <lay-col md="24">
          <lay-quote size="sm">
            <lay-row>
              <lay-col md="6"><h3>AI测分转自动化用例</h3></lay-col>
              <lay-col md="6"><lay-button @click="queryConfig">新增项目配置</lay-button></lay-col>
            </lay-row>
          </lay-quote>
        </lay-col>
      </lay-row>
      <lay-layer v-model="visible" title="新增项目配置" :footer="false" :shade="false" :area="['600px', '650px']">
         <lay-row>
           <lay-col md="8">
              <lay-select
                v-model="params.projectName"
                placeholder="请选择项目"
                @change="queryConfig"
                allow-clear
                size="sm"
                style="width: 80%"
              >
                <lay-select-option :value="unit.value" :label="unit.name" v-for="unit in projects"></lay-select-option>
              </lay-select>
           </lay-col>
           <lay-col>
              <lay-button size="sm" type="primary" @click="btn_save">保存</lay-button>
           </lay-col>
         </lay-row>
<!--        https://devpress.csdn.net/vue/66cd7cd41016441633674019.html-->
        <json-editor-vue
          @update:modelValue="updataModel"
          :modeList="modeList"
          :currentMode="'form'"
          class="editor"
          v-model="projectConfig"
          style="height: 560px; position: relative"
        />
      </lay-layer>
      <lay-row space="20">
        <lay-col md="1"></lay-col>
        <lay-col md="20">
            <lay-form :model="params" ref="layFormRef4" required>
              <lay-row space="5">
                <lay-col md="12">
                  <lay-form-item label="项目名称" prop="project">
                    <lay-select
                        v-model="params.projectName"
                        placeholder="请选择项目"
                        style="width: 100%"
                        allow-clear
                    >
                      <lay-select-option :value="unit.value" :label="unit.name" v-for="unit in projects"></lay-select-option>
                    </lay-select>
                  </lay-form-item>
                </lay-col>
              </lay-row>
              <lay-row space="5">
                <lay-col md="12">
                  <lay-form-item label="用例路径" prop="nodePath">
                    <lay-input
                        v-model="params.nodePath"
                        placeholder="请拷贝blade测试用例节点的路径进行粘贴"
                        allow-clear
                    ></lay-input>
                  </lay-form-item>
                  </lay-col>
<!--                  <lay-col md="12">-->
<!--                    <lay-form-item label="提供数据" prop="dataFlag">-->
<!--                      <lay-checkbox name="like" value="1" v-model="prepareDataFlag">-->
<!--                        {{ prepareDataFlag ? '是' : '否' }}-->
<!--                      </lay-checkbox>-->
<!--                    </lay-form-item>-->
<!--                  </lay-col>-->
              </lay-row>
               <lay-row space="5">
                <lay-col md="12">
                  <lay-form-item label="个人账号" prop="account" v-if="params.projectName === 'noproject' ">
                    <lay-input
                        v-model="params.account"
                        placeholder="请输入域账号"
                        allow-clear
                    ></lay-input>
                  </lay-form-item>
                  </lay-col>
              </lay-row>
              <lay-row space="5">
                <lay-col md="12">
                  <lay-form-item label="项目授权码" prop="apiToken" v-if="params.projectName === 'noproject' ">
                    <lay-input
                        v-model="params.apiToken"
                        placeholder="请输入需要生成用例的blade项目授权码"
                        allow-clear
                    ></lay-input>
                  </lay-form-item>
                  </lay-col>
              </lay-row>
              <lay-row space="5">
                <lay-col :md="prepareDataFlag ? 12 : 24">
                  <lay-form-item label="测分内容" prop="content">
                    <lay-textarea
                        style="height: 400px"
                        v-model="params.content"
                        placeholder="请从blade上导出测分点内容进行粘贴-因AI大模型限流原因（<10次/min），测分点不宜太长"
                        allow-clear
                    ></lay-textarea>
                  </lay-form-item>
                </lay-col>
<!--                <lay-col :md="prepareDataFlag ? 12 : 0">-->
<!--                  <lay-form-item label="测试数据" prop="prepareData" v-if="prepareDataFlag">-->
<!--                    <lay-textarea-->
<!--                        style="height: 400px"-->
<!--                        v-model="params.prepareData"-->
<!--                        placeholder="请从数据库拷贝1-2行的JSON格式测试数据粘贴进来！"-->
<!--                        allow-clear-->
<!--                    ></lay-textarea>-->
<!--                  </lay-form-item>-->
<!--                </lay-col>-->
              </lay-row>
              <lay-row space="5">
                <lay-col md="24">
                  <lay-form-item style="text-align: center;">
                    <lay-button @click="resetData">重置</lay-button>
                    <lay-button type="normal" @click="submitFile">提交</lay-button>
                  </lay-form-item>
                  <lay-form-item label="转化进度" v-if="displayFlag">
                      <div style="height: 20px"></div>
                      <lay-progress
                          show-text="转化进度"
                          :percent="progress"
                      ></lay-progress>
                  </lay-form-item>
                </lay-col>
              </lay-row>

            </lay-form>
        </lay-col>
      </lay-row>
    </lay-card>
</template>

<script lang="ts">
export default {
    name: "AICases"
}
</script>

<script lang="ts" setup>
import {onMounted, onUnmounted, reactive, ref} from "vue";
import {notify} from "../../../untils/tip";
import {layer} from "@layui/layer-vue";
import {
  queryProgressApi,
  queryProjectConfigApi,
  queryProjectsApi,
  submitConfigApi,
  submitTaskApi
} from "../../../api/fastApi/AiCase";


onMounted(() => {
  queryProjectMethod();
})

const projects = ref([
    {value: 'noproject', name: '未配置项目'},
    {value: 'aml5', name: '反洗钱5.0'},
    {value: 'urp3', name: '报送3.0'},
    {value: 'others', name: '赛题Demo'},
]);

const visible = ref(false);
const displayFlag = ref(false);
const prepareDataFlag = ref(false);
const progress = ref(0)
const params = reactive({
    nodePath: '',
    content: '',
    projectName: '',
    apiToken: '',
    account: '',
    prepareData: '',
})

// 数据更新时触发
const updataModel = (val: any) => {
  prepareDataFlag.value = val;
};
const errors = ref();
const line = ref();

const layerId = ref();
const caseRunning = function() {
    layerId.value = layer.load(0, { time: 1000 * 60 * 10 })
}

// 保存修改
const btn_save = async () => {
  console.log('save')
  const {code, data, success} = await submitConfigApi(prepareDataFlag.value);
  if(success === true){
    notify("success", '新增配置成功！');
    await queryProjectMethod();
    visible.value = false;
  }
};

const options = ref({
    search: false,
    history: false,
})
const modeList= ref(["view", "code", "form"]) // 可选模式

const taskId = ref("");
const projectConfig = ref({})

const countInsert = ref(0);
const timerInsert = ref();

const resetData = () => {
  params.nodePath = '';
  params.prepareData = '';
  params.content = '';
  // params.prepareData = ''
}

const queryConfig = async () => {
  if(params.projectName === ''){
    params.projectName = 'example';
  }
  // 查询项目配置
  const {code, data, success} = await queryProjectConfigApi({name: params.projectName});
  if(success === true){
    projectConfig.value = data;
    notify("success", '获取配置成功！');
    visible.value = true;
  }
}

const queryProjectMethod = async () => {
  const {code, data, success} = await queryProjectsApi({});
  if(success === true){
    projects.value = JSON.parse(data);
  }else {
    notify("failed", "查询项目列表失败！");
  }
}

const queryProgress = async () => {
    let {code, data, success} = await queryProgressApi({taskId: taskId.value});
    if(success === true){
       progress.value = Number(data);
       console.log('current progress : ', progress.value);
       if(Number(data) >= 100){
          clearInterval(timerInsert.value);
          notify("success", '用例转换＆上传完成！')
          layer.close(layerId.value);
       }
    }
    countInsert.value ++;
    if(countInsert.value > 600){
      clearInterval(timerInsert.value);
      notify("failed", "超时退出！")
    }
}


const layId = ref()
const submitFile = async () => {
  console.log("submit content :　", params);
  progress.value = 0;
  if(params.projectName === '' || params.nodePath === '' || params.content === ''){
    notify("failed", "项目名称或用例路径或测分内容为空！");
  }else {
      caseRunning();
      let response = await submitTaskApi(params);
      layer.close(layId.value);
      if (response.success === true) {
        taskId.value = response.data;
        notify('success', '用例转换生成中，请等待...');
        displayFlag.value = true;
        countInsert.value = 0;
        timerInsert.value = setInterval(queryProgress, 2000)
      } else {
        notify('fail', '响应失败！');
      }
  }
};


// 销毁前清理定时任务
onUnmounted(() => {
  if(timerInsert.value){
    clearInterval(timerInsert.value);
  }
  timerInsert.value = ''
})
</script>

<style scoped>

</style>